package cn.lovemmd.model.util;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.crypto.SecretKey;

import org.springframework.stereotype.Component;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;

/**
 * JWT工具类
 * 用于生成和验证下载token
 * 
 * @author TLS
 * @since 2024-01-01
 */
@Component
public class JwtUtil {

    private static final String SECRET_KEY = "your-secret-key-must-be-at-least-256-bits-long-for-security";
    private static final long TOKEN_EXPIRE_TIME = 5 * 60 * 1000; // 5分钟过期
    private static final SecretKey key = Keys.hmacShaKeyFor(SECRET_KEY.getBytes());

    /**
     * 生成下载token
     * 
     * @param modelId 模型ID
     * @param userId 用户ID（可选）
     * @param ip IP地址
     * @return JWT token
     */
    public String generateDownloadToken(Long modelId, String userId, String ip) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("modelId", modelId);
        claims.put("userId", userId);
        claims.put("ip", ip);
        claims.put("type", "download");
        
        return Jwts.builder()
                .setClaims(claims)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + TOKEN_EXPIRE_TIME))
                .signWith(key, SignatureAlgorithm.HS256)
                .compact();
    }

    /**
     * 验证token
     * 
     * @param token JWT token
     * @return 验证结果
     */
    public boolean validateToken(String token) {
        try {
            Jwts.parserBuilder()
                    .setSigningKey(key)
                    .build()
                    .parseClaimsJws(token);
            return true;
        } catch (JwtException | IllegalArgumentException e) {
            return false;
        }
    }

    /**
     * 从token中获取模型ID
     * 
     * @param token JWT token
     * @return 模型ID
     */
    public Long getModelIdFromToken(String token) {
        try {
            Claims claims = Jwts.parserBuilder()
                    .setSigningKey(key)
                    .build()
                    .parseClaimsJws(token)
                    .getBody();
            return claims.get("modelId", Long.class);
        } catch (JwtException | IllegalArgumentException e) {
            return null;
        }
    }

    /**
     * 从token中获取IP地址
     * 
     * @param token JWT token
     * @return IP地址
     */
    public String getIpFromToken(String token) {
        try {
            Claims claims = Jwts.parserBuilder()
                    .setSigningKey(key)
                    .build()
                    .parseClaimsJws(token)
                    .getBody();
            return claims.get("ip", String.class);
        } catch (JwtException | IllegalArgumentException e) {
            return null;
        }
    }

        /**
     * 检查token是否过期
     *
     * @param token JWT token
     * @return 是否过期
     */
    public boolean isTokenExpired(String token) {
        try {
            Claims claims = Jwts.parserBuilder()
                    .setSigningKey(key)
                    .build()
                    .parseClaimsJws(token)
                    .getBody();
            return claims.getExpiration().before(new Date());
        } catch (JwtException | IllegalArgumentException e) {
            return true;
        }
    }

    /**
     * 生成用户登录token（24小时有效期）
     *
     * @param username 用户名
     * @return JWT token
     */
    public String generateUserToken(String username) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("username", username);
        claims.put("type", "user");
        
        return Jwts.builder()
                .setClaims(claims)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + 24 * 60 * 60 * 1000)) // 24小时
                .signWith(key, SignatureAlgorithm.HS256)
                .compact();
    }

    /**
     * 从token中获取用户名
     *
     * @param token JWT token
     * @return 用户名
     */
    public String getUsernameFromToken(String token) {
        try {
            Claims claims = Jwts.parserBuilder()
                    .setSigningKey(key)
                    .build()
                    .parseClaimsJws(token)
                    .getBody();
            return claims.get("username", String.class);
        } catch (JwtException | IllegalArgumentException e) {
            return null;
        }
    }
}
